<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="采购计划编号" prop="sn">
        <el-input
          v-model="queryParams.sn"
          placeholder="请输入采购计划编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['procurementmanagement:plan:add']"
        >新增</el-button>
      </el-col>
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="success"-->
<!--          plain-->
<!--          icon="el-icon-edit"-->
<!--          size="mini"-->
<!--          :disabled="single"-->
<!--          @click="handleUpdate"-->
<!--          v-hasPermi="['procurementmanagement:plan:edit']"-->
<!--        >修改</el-button>-->
<!--      </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['procurementmanagement:plan:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="planList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键ID" align="center" prop="id" />
      <el-table-column label="采购计划编号" align="center" prop="sn"  width="200px"/>
      <el-table-column label="部门名称" align="center" prop="deptName" />
      <el-table-column label="编制人员" align="center" prop="formationPerson" />
      <el-table-column label="编制时间" align="center" prop="formationTime" width="100px">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.formationTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="采购说明" align="center" prop="procurementDesc" width="200px"/>
      <el-table-column label="供应商名称" align="center" prop="supplierName"  width="100px"/>
      <el-table-column label="集合供应时间" align="center" prop="supplierTime" width="100px">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.supplierTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="100px">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['procurementmanagement:plan:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['procurementmanagement:plan:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改采购计划(es_procurement_plan)对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="采购计划编号" prop="sn">
          <el-input
            v-model="form.sn"
            placeholder="采购计划编号"
            disabled
            style="width: 220px"
          ></el-input>
        </el-form-item>
        <el-form-item label="所属部门">
          <el-cascader
            v-model="form.deptId"
            :options="deptTree"
            :props="{ checkStrictly: true, value: 'id', label: 'name' }"
            placeholder="请选择所属部门"
            @change="handleDeptChange">
          </el-cascader>
        </el-form-item>
        <el-form-item label="编制人">
          <el-cascader
            v-model="form.formationPersonId"
            :options="personList"
            :props="{ checkStrictly: true, value: 'id', label: 'realName' }"
            placeholder="请选择编制人"
            @change="handleCreatorChange">
          </el-cascader>
        </el-form-item>

        <el-form-item label="编制时间" prop="formationTime">
          <el-date-picker clearable
            v-model="form.formationTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择编制时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="采购说明" prop="procurementDesc">
          <el-input v-model="form.procurementDesc" type="textarea" placeholder="请输入内容" style="width: 350px" />
        </el-form-item>
        <el-form-item label="供应商名称" prop="supplierName">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-search"
            @click="handleSupplierDialog"
          > {{ form.supplierName || '请选择供应商' }}</el-button>
        </el-form-item>
        <el-form-item label="集合供应时间" prop="supplierTime">
          <el-date-picker clearable
            v-model="form.supplierTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择集合供应时间">
          </el-date-picker>
        </el-form-item>

        <el-row :gutter="10" class="mb8">
          <!-- 其他按钮省略 -->
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-search"
              size="mini"
              @click="handleSelectGoods"
              v-hasPermi="['procurementmanagement:goods:select']"
            >选择商品</el-button>
          </el-col>
        </el-row>

        <!-- 采购明细表格 -->
        <el-table :data="selectedGoods" border style="width: 100%; margin-bottom: 20px">
          <el-table-column prop="sn" label="商品编号" width="120"></el-table-column>
          <el-table-column prop="name" label="商品名称" width="150"></el-table-column>
          <el-table-column prop="specNames" label="规格型号" width="120"></el-table-column>
          <el-table-column prop="categoryName" label="商品类别" width="120"></el-table-column>
          <el-table-column label="计划采购数量" width="120">
            <template slot-scope="scope">
              <el-input-number
                v-model="scope.row.planQuantity"
                :min="1"
                size="mini"
                placeholder="数量">
              </el-input-number>
            </template>
          </el-table-column>
          <el-table-column label="计划供应时间" width="150">
            <template slot-scope="scope">
              <el-date-picker
                v-model="scope.row.supplyTime"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="选择供应时间"
                size="mini">
              </el-date-picker>
            </template>
          </el-table-column>
          <el-table-column label="成本价" width="120">
            <template slot-scope="scope">
              <el-input-number
                v-model="scope.row.costPrice"
                :min="0"
                :precision="2"
                size="mini"
                placeholder="成本价">
              </el-input-number>
            </template>
          </el-table-column>
          <el-table-column label="税率" width="120">
            <template slot-scope="scope">
              <el-input-number
                v-model="scope.row.taxRate"
                :min="0"
                :max="1"
                :step="0.01"
                :precision="2"
                size="mini"
                placeholder="税率">
              </el-input-number>
            </template>
          </el-table-column>
          <el-table-column prop="remark" label="备注">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.remark"
                size="mini"
                placeholder="备注">
              </el-input>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="80">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleRemoveGoods(scope.$index)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 供应商选择器弹出窗口 -->
    <el-dialog :visible.sync="supplierDialogVisible" title="选择供应商" width="1000px">
      <el-table :data="supplierList">
        <el-table-column label="选择" width="55">
          <template slot-scope="scope">
            <el-radio
              v-model="selectedSupplierId"
              :label="scope.row.id"
              @change="handleSupplierRadioChange(scope.row)"
              class="custom-radio"
            ></el-radio>
          </template>
        </el-table-column>
        <el-table-column prop="customName" label="供应商名称"></el-table-column>
        <el-table-column prop="customSn" label="供应商编码"></el-table-column>
        <el-table-column prop="productionAddress" label="地址"></el-table-column>
        <el-table-column prop="transfer" label="传真"></el-table-column>
        <el-table-column prop="linkman" label="联系人"></el-table-column>
        <el-table-column prop="telephone" label="电话"></el-table-column>
        <el-table-column prop="email" label="电子邮件"></el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="supplierDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmSupplierSelection">确定</el-button>
      </div>
    </el-dialog>

    <!-- 商品选择对话框 -->
    <el-dialog :visible.sync="goodsDialogVisible" title="选择商品">
      <el-table :data="goodsList" @selection-change="handleGoodsSelectionChange">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="sn" label="商品编号"></el-table-column>
        <el-table-column prop="name" label="商品名称"></el-table-column>
        <el-table-column prop="categoryName" label="商品类别"></el-table-column>
        <el-table-column prop="specNames" label="规格型号"></el-table-column>
        <el-table-column prop="totalStock" label="库存"></el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
          <el-button @click="cancelGoodsSelection">取消</el-button>
          <el-button type="primary" @click="confirmGoodsSelection">确定</el-button>
        </div>
    </el-dialog>

  </div>
</template>

<script>
import {
  listPlan,
  getPlan,
  delPlan,
  addPlan,
  updatePlan,
  getDeptTree,
  getCompiler, getSupplierList, getsupplierListBid
} from "@/api/procurementmanagement/plan";
import { listGoods } from "@/api/goods/goods";

export default {
  name: "Plan",
  name2: "GoodsSelect",
  data() {
    return {
      selectedSupplierId: null,
      originalSelectedGoods:[],
      // 已选择的商品列表（修改为包含更多字段的对象数组）
          selectedGoods: [],
      // 商品选择对话框可见性
      goodsDialogVisible: false,
      // 已选择的商品列表
      selectedGoods: [],
      // 商品列表
      goodsList: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedSystemDept: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 采购计划(es_procurement_plan)表格数据
      planList: [],
      // 部门表格数据
      systemDeptList: [],
      //二级部门
      deptTree: [],
      //制表人
      personList:[],
      supplierDialogVisible: false,
      selectedSupplier: null,
      //供应商
      supplierList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        sn: null,
        deptId: null,
        deptName: null,
        formationPersonId: null,
        formationPerson: null,
        formationTime: null,
        procurementDesc: null,
        supplierId: null,
        supplierName: null,
        supplierTime: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    this.getList();
    // 监听补货计划生成事件
      this.$on('plan-generated', this.onPlanGenerated);
  },
  beforeDestroy() {
    // 移除事件监听
    this.$off('plan-generated', this.onPlanGenerated);
  },
  methods: {
    onPlanGenerated() {
        this.getList(); // 刷新列表
      },
    /** 查询采购计划(es_procurement_plan)列表 */
    getList() {
      this.loading = true;
      listPlan(this.queryParams).then(response => {
        this.planList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        sn: null,
        deptId: null,
        deptName: null,
        formationPersonId: null,
        formationPerson: null,
        formationTime: null,
        procurementDesc: null,
        createTime: null,
        supplierId: null,
        supplierName: null,
        supplierTime: null
      };
      this.selectedGoods = []; // 重置选择的商品
      this.systemDeptList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    handleSupplierRadioChange(row) {
      this.selectedSupplier = row;
      this.selectedSupplierId = row.id; // 手动设置选中的供应商ID
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.getDeptTree(); // 获取部门树
      this.getCompiler();
      this.open = true;
      this.title = "添加采购计划(es_procurement_plan)";
      // 初始化采购计划编号
      this.generatePlanNumber();
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getPlan(id).then(response => {
        this.form = response.data;
        // 初始化已选择的商品
        if (response.data.productList) {
          this.selectedGoods = response.data.productList.map(item => ({
            id: item.goodsId,
            name: item.goodsName,
            sn: item.goodsSn,
            specNames: item.specification,
            categoryId: item.categoryId,
            categoryName: item.categoryName,
            planQuantity: item.procurementNum,
            remark: item.remark,
            supplyTime: item.supplyTime,
            costPrice: item.costPrice,
            taxRate: item.taxRate
          }));
        }
        this.systemDeptList = response.data.systemDeptList;
        this.getDeptTree(); // 获取部门树
        this.getCompiler(); // 获取编制人
        this.open = true;
        this.title = "修改采购计划(es_procurement_plan)";
      });
    },

     // 移除商品
      handleRemoveGoods(index) {
        this.selectedGoods.splice(index, 1);
      },

      // 修改 confirmGoodsSelection 方法
      confirmGoodsSelection() {
        if (this.selectedGoods.length > 0) {
          // 为每个商品添加计划采购数量和备注字段
          this.selectedGoods = this.selectedGoods.map(goods => {
            return {
              ...goods,
              planQuantity: goods.planQuantity || 1, // 默认数量为1
              remark: goods.remark || '' // 默认备注为空
            };
          });

          this.goodsDialogVisible = false;
          this.$message.success(`已选择 ${this.selectedGoods.length} 个商品`);
        } else {
          this.$message.warning("请选择至少一个商品");
        }
      },

    generatePlanNumber() {
      const prefix = "PL"; // 编号前缀
      const formationTime = this.form.formationTime || new Date().toISOString().slice(0, 10); // 获取编制时间，如果没有则使用当前日期
      const formattedDate = formationTime.replace(/-/g, ""); // 格式化为 YYYYMMDD

      // 调用后端接口获取当天的采购计划数量
      this.getPlanCountByDate(formationTime).then(count => {
        const seq = count + 1; // 当天的采购计划数量加1
        const formattedSeq = String(seq).padStart(4, "0"); // 序列号格式化为 0001
        this.form.sn = `${prefix}${formattedDate}${formattedSeq}`; // 拼接编号
      });
    },
    getPlanCountByDate(date) {
      // 调用后端接口获取当天的采购计划数量
      return new Promise((resolve, reject) => {
        listPlan({ formationTime: date }).then(response => {
          resolve(response.total); // 返回当天的采购计划数量
        }).catch(error => {
          console.error("获取采购计划数量失败", error);
          resolve(0); // 如果失败，默认返回0
        });
      });
    },
    // 获取部门树
    getDeptTree() {
      getDeptTree().then(response => {
        console.log(response.data)
        this.deptTree = response.data;
      });
    },
    //获取编制人
    getCompiler(){
      getCompiler().then(response => {
        this.personList = response.data;
      })
    },
    // 打开供应商选择器
    handleSupplierDialog() {
      this.getSupplierList();
      this.supplierDialogVisible = true;
    },

// 获取供应商列表
    getSupplierList() {
      getSupplierList().then(response => {
        this.supplierList = response.data;
      });
    },

// 处理供应商行点击事件
    handleSupplierRowClick(row) {
      this.selectedSupplier = row; // 保存当前选中的供应商
    },
    // 确认选择供应商
    confirmSupplierSelection() {
      if (this.selectedSupplier) {
        this.form.supplierName = this.selectedSupplier.customName;
        this.form.supplierId = this.selectedSupplier.id;
        this.supplierDialogVisible = false;
      } else {
        this.$message.warning("请选择一个供应商");
      }
    },
    handleCreatorChange(value) {
      if (value.length > 0) {
        // 获取选中项的最后一个值作为 id
        const selectedPerson = this.personList.find(person => person.id.toString() === value[value.length - 1].toString());
        if (selectedPerson) {
          this.form.formationPersonId = selectedPerson.id; // 保存编制人 ID 到表单
          this.form.formationPerson = selectedPerson.realName; // 保存编制人名称到表单
        }
      } else {
        this.form.formationPersonId = null;
        this.form.formationPerson = null;
      }
    },
    handleDeptChange(value) {
      if (value.length > 0) {
        // 获取选中的最后一级部门的 ID
        const deptId = value[value.length - 1];
        // 根据 ID 查找对应的部门对象
        const selectedDept = this.findDeptById(this.deptTree, deptId);
        if (selectedDept) {
          this.form.deptId = selectedDept.id; // 保存子部门的 ID
          this.form.deptName = selectedDept.name; // 保存子部门的名称
        }
      } else {
        this.form.deptId = null;
        this.form.deptName = null;
      }
    },
// 根据 ID 查找部门对象
    findDeptById(tree, id) {
      for (let dept of tree) {
        if (dept.id === id) {
          return dept; // 如果找到匹配的 ID，返回该部门对象
        }
        if (dept.children && dept.children.length > 0) {
          const result = this.findDeptById(dept.children, id); // 递归查找子部门
          if (result) return result;  // 如果在子部门中找到，返回结果
        }
      }
      return null; // 如果未找到，返回 null
    },

    // 打开商品选择对话框
    handleSelectGoods() {
      // 保存当前的商品列表
      this.originalSelectedGoods = [...this.selectedGoods];
      this.getGoodsList();
      this.goodsDialogVisible = true;
    },
    // 获取商品列表
    getGoodsList() {
      listGoods().then(response => {
        this.goodsList = response.rows;
        console.log("商品列表:", this.goodsList); // 调试输出
      }).catch(error => {
        console.error("获取商品列表失败", error);
        this.$message.error("获取商品列表失败");
      });
    },
    // 处理商品选择变化
    handleGoodsSelectionChange(selection) {
      this.selectedGoods = selection;
    },
    // 确认选择商品
    confirmGoodsSelection() {
      if (this.selectedGoods.length > 0) {
        // 为每个商品添加计划采购数量和备注字段
        this.selectedGoods = this.selectedGoods.map(goods => {
          return {
            ...goods,
            planQuantity: goods.planQuantity || 1, // 默认数量为1
            remark: goods.remark || '', // 默认备注为空
            supplyTime: goods.supplyTime || null,
            costPrice: goods.costPrice || 0,
            taxRate: goods.taxRate || 0
          };
        });
        this.goodsDialogVisible = false;
        this.$message.success(`已选择 ${this.selectedGoods.length} 个商品`);
      } else {
        this.$message.warning("请选择至少一个商品");
      }
    },

    cancelGoodsSelection() {
      // 恢复原始的商品列表
      this.selectedGoods = [...this.originalSelectedGoods];
      this.goodsDialogVisible = false;
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 准备采购明细数据
          const productList = this.selectedGoods.map(goods => ({
            goodsId: goods.id,
            goodsName: goods.name,
            goodsSn: goods.sn,
            specification: goods.specNames,
            categoryId: goods.categoryId,
            categoryName: goods.categoryName,
            procurementNum: goods.planQuantity,
            supplyTime: goods.supplyTime,
            remark: goods.remark,
            costPrice: goods.costPrice,
            taxRate: goods.taxRate
          }));

          // 将选择的商品添加到表单数据中
          this.form.productList = productList;

          if (this.form.id != null) {
            updatePlan(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPlan(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除采购计划(es_procurement_plan)编号为"' + ids + '"的数据项？').then(function() {
        return delPlan(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
	/** 部门序号 */
    rowSystemDeptIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    /** 部门添加按钮操作 */
    handleAddSystemDept() {
      let obj = {};
      obj.name = "";
      obj.sn = "";
      obj.parentId = "";
      obj.regionIds = "";
      obj.regionNames = "";
      obj.type = "";
      obj.sort = "";
      obj.remark = "";
      obj.creator = "";
      obj.updater = "";
      obj.deleted = "";
      this.systemDeptList.push(obj);
    },
    /** 部门删除按钮操作 */
    handleDeleteSystemDept() {
      if (this.checkedSystemDept.length == 0) {
        this.$modal.msgError("请先选择要删除的部门数据");
      } else {
        const systemDeptList = this.systemDeptList;
        const checkedSystemDept = this.checkedSystemDept;
        this.systemDeptList = systemDeptList.filter(function(item) {
          return checkedSystemDept.indexOf(item.index) == -1
        });
      }
    },
    /** 复选框选中数据 */
    handleSystemDeptSelectionChange(selection) {
      this.checkedSystemDept = selection.map(item => item.index)
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('procurementmanagement/plan/export', {
        ...this.queryParams
      }, `plan_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>

<style scoped>
/* 完全隐藏单选按钮的所有标签内容 */
.custom-radio ::v-deep .el-radio__label {
  display: none !important;
  width: 0;
  height: 0;
  overflow: hidden;
}
</style>
